package me.illtamer.infinite.config;

import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 配置文件处理类
 * @author IllTamer
 */
class ConfigLoader {

    private final File path;
    private final String name;
    private File file;
    private FileConfiguration config;

    protected ConfigLoader(File folder, String name) {
        this.path = folder;
        this.name = name;
        this.config = load();
    }


    public void save() {
        try {
            config.save(this.file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.config = load();
    }


    private FileConfiguration load() {
        File file = new File(path, this.name);
        if (!file.exists()) {
            saveResource(this.name, false);
        }
        YamlConfiguration yaml = new YamlConfiguration();
        try {
            yaml.load(file);
            this.file = file;
        } catch (InvalidConfigurationException | IOException e) {
            e.printStackTrace();
        }
        return yaml;
    }

    public void reload() {
        this.config = load();
    }

    public FileConfiguration getConfig() {
        return config;
    }

    private void saveResource(String resourcePath, boolean replace) {
        if (resourcePath == null || "".equals(resourcePath))
            throw new IllegalArgumentException("ResourcePath cannot be null or empty");

        resourcePath = resourcePath.replace('\\', '/');
        InputStream in = getResource(resourcePath);
        if (in == null)
            throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + file);

        File outFile = new File(path, resourcePath);
        int lastIndex = resourcePath.lastIndexOf('/');
        File outDir = new File(path, resourcePath.substring(0, Math.max(lastIndex, 0)));

        if (!outDir.exists()) {
            outDir.mkdirs();
        }

        try {
            if (!outFile.exists() || replace) {
                OutputStream out = new FileOutputStream(outFile);
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.close();
                in.close();
            } else {
                System.out.println("Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
            }
        } catch (IOException ex) {
            System.out.println("Could not save " + outFile.getName() + " to " + outFile);
        }
    }

    public InputStream getResource(String filename) {
        if (filename == null)
            throw new IllegalArgumentException("File name cannot be null");
        try {
            URL url = this.getClass().getClassLoader().getResource(filename);
            if (url == null) return null;
            URLConnection connection = url.openConnection();
            connection.setUseCaches(false);
            return connection.getInputStream();
        } catch (IOException ex) {
            return null;
        }
    }
}
